Skip to content

Keep type arguments when narrowing a generic type to a subclass - #6562

Open
miguelmeloninnatial wants to merge 3 commits into
phpstan:2.3.xfrom
miguelmeloninnatial:bug-15289
Open

miguelmeloninnatial wants to merge 3 commits into
phpstan:2.3.xfrom
miguelmeloninnatial:bug-15289

Conversation

@miguelmeloninnatial

@miguelmeloninnatial miguelmeloninnatial commented Sep 23, 2026 •

Copy link
Copy Markdown

When a generic type is narrowed to a subclass, the subclass now keeps the type arguments that the generic type implies for it:

A subclass stays bare when the generic type does not determine all of its arguments, or when the generic type has call-site variance.

The first commit fixes an older, separate bug that the second commit reaches: a class name compared with a class-string of a parameterized class (class-string<Box<string>> against Box::class, with Box final) did not narrow, and a match over it reported the class as unhandled. Without it, testBug14412 fails after the second commit. The third commit extends it to a class-string with call-site variance, such as class-string<X<*>>.

With the source of 2.3.x, each new test fails on the bug that it covers, except one. MatchExpressionRuleTest::testBug15289 passes there too. It checks that a match over Some and None stays exhaustive after the change.

The issue bot shows the effect on three more open issues:

The espocrm integration job reports one new error, and it is a true positive. RecordBase::getRecordService() returns Espo\Core\Record\Service<Espo\ORM\Entity>. After instanceof Espo\Services\RecordTree, the value is now Espo\Services\RecordTree<Espo\ORM\Entity>. But Espo\Core\Controllers\RecordTree::getRecordTreeService() declares Espo\Services\RecordTree<Espo\Core\ORM\Entity>, and TEntity is invariant. Before, the narrowing dropped the argument and hid the mismatch. The expected errors live in phpstan/phpstan, so this PR cannot update them.

Without guards, the second commit made three benchmarks worse. Its two specializeSubclass() calls in TypeCombinator::intersect() cost about 5M instructions each in benchSpecifyShortTernary and in benchListOfClosures@closures-64. Its call on the path of TypeCombinator::union(), in intersectWithSubtractedType(), loaded GenericObjectType during the measured analysis of bug-4300.php, which added 64 KiB of memory. An instanceof GenericObjectType guard before each call removes all three. The measurements come from Tally, run locally:

Benchmark 2.3.x Without the guards This PR
TypeSpecifierBench::benchSpecifyShortTernary (instructions) 188,119,744 193,353,885 188,176,014
ConstantArrayTypeBuilderBench::benchListOfClosures@closures-64 (instructions) 62,905,714 67,835,325 62,902,713
AnalysisBench::benchAnalyse@bug-4300.php (memory, bytes) 264,272 329,808 264,272

The guards add an entry of three phpstanApi.instanceofType errors for TypeCombinator.php to the baseline, and the first commit raises the count for GenericObjectType.php from 4 to 5. GenericObjectType names no replacement for instanceof. Each guard makes the same check that specializeSubclass() makes first, so a guard cannot change a result.

The four changed source classes are shadowed by turbo-ext, and each commit makes the same change in their C++ mirrors. The guards exist only in PHP, because specializeSubclass() returns a type that is not a GenericObjectType unchanged.

Closes phpstan/phpstan#15289
Closes phpstan/phpstan#15266
Closes phpstan/phpstan#9189

@miguelmeloninnatial
miguelmeloninnatial force-pushed the bug-15289 branch 2 times, most recently from 576db25 to b0572ce Compare September 23, 2026 14:34
@miguelmeloninnatial
miguelmeloninnatial marked this pull request as ready for review September 23, 2026 15:22
@phpstan-bot

Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

@ondrejmirtes
ondrejmirtes changed the base branch from 2.2.x to 2.3.x November 1, 2026 11:53
A class name carries no type arguments.
`ConstantStringType::isSuperTypeOf()` and
`GenericClassStringType::isSuperTypeOf()` compared it as a bare `ObjectType`
with the generic type of a class-string, and `Box<string>` is only maybe a
supertype of a bare `Box`. So with a final `Box`,
`$c === Box::class` did not narrow a `class-string<Box<string>>` to never in
the else branch, and a `match` over it reported the class as unhandled.

The class name now gets the type arguments that the generic type implies for
it, through the new `GenericObjectType::specializeSubclass()`. A class that
is not generic, such as one that implements `Option<string>`, is still not
a value of `class-string<Option<int>>`.

Amp-Thread-ID: https://ampcode.com/threads/T-01a196f7-a83c-7170-a45b-f1d9db4220df
@miguelmeloninnatial
miguelmeloninnatial force-pushed the bug-15289 branch 2 times, most recently from f557c22 to df57b6c Compare November 17, 2026 10:12
A generic class written without type arguments is a subtype of every
parameterization of its ancestors, so `TypeCombinator::intersect()` kept the
bare subclass and dropped the arguments: `instanceof Some` narrowed an
`Option<int>` to `Some`, and so did `is_a()`, `@phpstan-assert` and
`$o::class` comparisons. Since `GenericObjectType::changeSubtractedType()`
returns the lone remaining subtype of a sealed hierarchy (phpstan#5369), that
subtype lost its arguments too: `Result<int, string>` without `Ok` became
`Err`. The merge after the branch no longer hid the loss, so a wrong return
type was accepted.

Both now take the arguments that the generic type implies for the subclass.
A subclass stays bare when the generic type does not determine all of its
arguments or has call-site variance. In a union, a bare subtracted subclass
is read within its type: `Option<int>~Some` together with `Some<int>` gives
`Option<int>`.

Amp-Thread-ID: https://ampcode.com/threads/T-01a196f7-a83c-7170-a45b-f1d9db4220df
A class name compared with a class-string of its own generic class now
takes the type arguments and the call-site variance of that class-string as
they are written: `X::class` read against `class-string<X<*>>` is `X<*>`.
So `$class !== X::class` narrows `class-string<X<*>>|class-string<Y<*>>` to
`class-string<Y<*>>`. Before, a class-string with call-site variance left
the class name bare, which is only maybe an `X<*>`, and nothing narrowed.

A subclass still stays bare when the class-string has call-site variance.
@miguelmeloninnatial

Copy link
Copy Markdown
Author

I force-pushed the branch. It is now three commits on 2.3.x, without the merge commit. The second commit now also holds the baseline entry for its instanceof guards. I also updated the description: it now explains the benchmark fix, the baseline entries and the espocrm error.

On beeb28b, all checks pass except four integration jobs:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants